package com.qef.com.mmovie.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.CountCallback;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.konifar.fab_transformation.FabTransformation;
import com.orhanobut.logger.Logger;
import com.qef.com.mmovie.App;
import com.qef.com.mmovie.R;
import com.qef.com.mmovie.api.NetApi;
import com.qef.com.mmovie.base.BaseBackFragment;
import com.qef.com.mmovie.entity.DataBean;
import com.qef.com.mmovie.entity.User;
import com.qef.com.mmovie.img.ImageLoader;
import com.qef.com.mmovie.mvp.adapter.CommentAdapter;
import com.qef.com.mmovie.utils.AnimatiorUtils;
import com.qef.com.mmovie.utils.DateUtil;
import com.qef.com.mmovie.utils.PopCreator;
import com.qef.com.mmovie.utils.PopWindowUtils;
import com.qef.com.mmovie.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;


/**
 * Created by qianenfan on 17/2/25.
 */

public class VideoDetailFragment extends BaseBackFragment implements Toolbar.OnMenuItemClickListener, View.OnClickListener {

    ImageView mImgDetail;
    Toolbar mToolbar;
    ImageView bgImage;
    TextView title;
    TextView type;
    TextView description;
    FloatingActionButton mFab;

    private int commentCount;
    private DataBean dataBean;
    private CollapsingToolbarLayout collToolBar;
    private JCVideoPlayerStandard mVideoPlayer;
    private RecyclerView rcCommon;
    private LinearLayout mView;
    int bgcolor;
    private List<AVObject> commontDatas;
    private TextView mTvCommentCount;

    public static VideoDetailFragment newInstance(DataBean dataBean) {

        Bundle args = new Bundle();
        args.putParcelable(ARG_ITEM, dataBean);
        VideoDetailFragment fragment = new VideoDetailFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dataBean = getArguments().getParcelable(ARG_ITEM);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.video_home_detail_fragment, container, false);
        initView(view);
        return view;
    }

    @SuppressLint("CutPasteId")
    private void initView(View view) {
        mView = (LinearLayout) view.findViewById(R.id.ll_comment);
        mTvCommentCount = (TextView) view.findViewById(R.id.tv_comment_count);
        mToolbar = ((Toolbar) view.findViewById(R.id.toolbar));
        mToolbar.setOnMenuItemClickListener(this);
        collToolBar = ((CollapsingToolbarLayout) view.findViewById(R.id.toolbar_layout));
        mImgDetail = (ImageView) view.findViewById(R.id.img_detail);
        bgImage = (ImageView) view.findViewById(R.id.bg_image);
        title = (TextView) view.findViewById(R.id.titlex);
        type = (TextView) view.findViewById(R.id.type);
        description = (TextView) view.findViewById(R.id.description);
        mFab = (FloatingActionButton) view.findViewById(R.id.fab);
        mVideoPlayer = (JCVideoPlayerStandard) view.findViewById(R.id.videoplayer);
        View btsheet = view.findViewById(R.id.design_bottom_sheet);
        mFab.setBackgroundTintList(new ColorStateList(new int[][]{new int[0]}, new int[]{0xffffcc00}));

        mToolbar.setTitle("");
        initToolbarNav(mToolbar);
        ImageLoader.loadAll(getActivity(), dataBean.getCover().getDetail(), mImgDetail);
        ImageLoader.loadAll(getActivity(), dataBean.getCover().getBlurred(), bgImage);
        title.setText(dataBean.getTitle());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("#").append(dataBean.getCategory())
                .append(" ")
                .append(" / ")
                .append(" ")
                .append(DateUtil.formatTime2(dataBean.getDuration()));
        type.setText(stringBuilder.toString());
        description.setText(dataBean.getDescription());

        mFab.setOnClickListener(v -> {
            if (mFab.getVisibility() == View.VISIBLE) {
                FabTransformation.with(mFab).setListener(new FabTransformation.OnTransformListener() {
                    @Override
                    public void onStartTransform() {
                    }

                    @Override
                    public void onEndTransform() {
                        mVideoPlayer.setUp(dataBean.getPlayUrl(), JCVideoPlayer.SCREEN_LAYOUT_LIST, "");
//                        mVideoPlayer.setUp(dataBean.getPlayUrl(), JCVideoPlayer.SCREEN_LAYOUT_LIST, "");
                        ImageView c = mVideoPlayer.thumbImageView;
                        ImageLoader.getInstance().displayLongImage(dataBean.getCover().getDetail(), App.getInstance(), c);
                        mVideoPlayer.setVisibility(View.VISIBLE);
                        mImgDetail.setVisibility(View.GONE);
                        mVideoPlayer.startVideo();
//                        JumpUtils.goToVideoPlayer(getActivity(), mImgDetail, dataBean);
                    }
                }).

                        transformTo(mImgDetail);
            }
        });

        initColor();
        setViewAnimator();

        view.findViewById(R.id.bt_comment).setOnClickListener(this);
        initData();
    }

    private void initData() {
        getCommentCount();
    }

    private void getCommentCount() {
        NetApi.getCommentCount(dataBean.getId(), new CountCallback() {
            @Override
            public void done(int i, AVException e) {
                commentCount = i;
                mTvCommentCount.setText(String.valueOf(i));
            }
        });
    }


    int color = 0xffffcc00;

    private void initColor() {

        Glide.with(getContext()).load(dataBean.getCover().getBlurred()).asBitmap().into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {

                Palette.from(resource).generate(palette -> {
                    try {
                        color = palette.getDarkMutedSwatch().getRgb();
                    } catch (Exception e) {
//                        LogUtil.d(e.getMessage());
                    }
                    collToolBar.setContentScrimColor(color);
                    mFab.setBackgroundTintList(new ColorStateList(new int[][]{new int[0]}, new int[]{color}));

                });

            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        FabTransformation.with(mFab).setListener(new FabTransformation.OnTransformListener() {
            @Override
            public void onStartTransform() {
            }

            @Override
            public void onEndTransform() {
                if (mImgDetail.getVisibility() == View.INVISIBLE) {
                    mImgDetail.setVisibility(View.VISIBLE);
                }
            }
        }).transformFrom(mImgDetail);
    }

    @Override
    public void onPause() {
        super.onPause();
        mVideoPlayer.release();

    }

    private void setViewAnimator() {
        AnimatiorUtils.setTextViewAlphAnimator(description);
        AnimatiorUtils.setTextViewAlphAnimator(type);
        AnimatiorUtils.setTextViewAlphAnimator(title);
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.collect:
                if (User.isLoginToLogin(getActivity())) {
                    NetApi.collection(dataBean, new SaveCallback() {
                        @Override
                        public void done(AVException e) {
                            ToastUtil.showToast(App.getInstance(), "收藏成功！");
                            mTvCommentCount.setText(String.valueOf(commentCount + 1));
                        }
                    });
                }
                return true;
            case R.id.add:
                ToastUtil.showToast(App.getInstance(), "分享按钮");
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_comment:
                actionComment();
                break;
        }
    }

    private void actionComment() {
        PopWindowUtils.with(getContext()).loadLayout(R.layout.commentlayout).initPopWindow().setOnCustomListener(new PopCreator.PopCustomkListener() {
            CommentAdapter commAdapter;

            @Override
            public void onCustom(View view, PopupWindow popupWindow) {
                popupWindow.setOutsideTouchable(false);
                popupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
                popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                rcCommon = (RecyclerView) view.findViewById(R.id.rc_comment);
                EditText commonEdit = (EditText) view.findViewById(R.id.common_edt);
                if (User.isLogin())
                    ImageLoader.getInstance().displayImage(App.getInstance(), User.getHead().toString(),
                            (ImageView) view.findViewById(R.id.iv_headx), 80, 80);
                view.setBackgroundColor(color);
                rcCommon.setBackgroundColor(color);
                commonEdit.setBackgroundColor(color);
                view.findViewById(R.id.iv_submit).setOnClickListener(view1 -> {
                    if (!User.isLoginToLogin(getActivity())) {
                        popupWindow.dismiss();
                        openKeyboard();
                        return;
                    }
                    if (commonEdit.getText().toString().length() != 0) {
                        NetApi.comment(dataBean.getId(), commonEdit.getText().toString().trim(),
                                new SaveCallback() {
                                    @Override
                                    public void done(AVException e) {
                                        ToastUtil.showToast(App.getInstance(), "评论成功！");
                                        getCommentData();
                                        commonEdit.setText("");
                                        openKeyboard();
                                    }
                                });
                    } else {
                        ToastUtil.showToast(App.getInstance(), "评论内容不能为空！");
                    }
                });
                LinearLayoutManager layout = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
                rcCommon.setLayoutManager(layout);
                commontDatas = new ArrayList<>();
                rcCommon.setAdapter(commAdapter = new CommentAdapter(getActivity(), commontDatas));
                getCommentData();
            }

            private void getCommentData() {
                commontDatas.clear();
                commAdapter.clear();
                NetApi.getComment(dataBean.getId(), new FindCallback() {
                    @Override
                    public void done(List list, AVException e) {
                        Logger.i(list.toString());
                        commontDatas.addAll(list);
                        commAdapter.addAll(list);
                    }
                });
            }

        }).ShowAsDropDown(mView, 100, 0, 0);
    }

    /**
     * 软键盘隐藏，显示则隐藏 反正显示
     */
    private void openKeyboard() {
        InputMethodManager imm = (InputMethodManager) getActivity()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }
}
